<?php

namespace app\admin\service;

use app\admin\model\Examlog;
use think\facade\Db;

/**
 * 训练题库管理-服务类
 * @author 小码哥
 * @since 2020/11/15
 * Class ExamlogService
 * @package app\admin\service
 */
class ExamlogService extends BaseService
{
    /**
     * 构造函数
     * @author 小码哥
     * @since 2020/11/15
     * ExamlogService constructor.
     */
    public function __construct()
    {
        $this->model = new Examlog();
    }

    /**
     * @return array
     * @throws \think\db\exception\DbException
     * 获取列表
     */
    public function getList()
    {
        $sort = 'id desc';
        // 常规查询条件
        $param = request()->param();
        $map = [];
        if ($param) {
            // 筛选标题
            if (isset($param['userinfo']) && $param['userinfo']) {
                $userids = Db::name('member')
                    ->where('realname|examinee_number|idcard', 'like', "%{$param['userinfo']}%")
                    ->column('id');
                $map[] = ['user_id', 'in', $userids];
            }
            if (isset($param['exam_id']) && $param['exam_id']) {
                $map[] = ['exam_id', '=', $param['exam_id']];
            }
            // 筛选状态
            if (isset($param['status']) && $param['status']) {
                $map[] = ['status', '=', $param['status']];
            }
        }
        // 设置查询条件
        if (is_array($map)) {
            $map[] = ['mark', '=', 1];
        } elseif ($map) {
            $map .= " AND mark=1 ";
        } else {
            $map .= " mark=1 ";
        }
        $count = $this->model
            ->where($map)
            ->count();
        $ids = $this->model
            ->where($map)
            ->order($sort)
            ->page(PAGE, PERPAGE)
            ->column("id");
        $map[] = ['id', 'in', $ids];
        $field = '';
        $list = $this->model->getAllInfo($map, $field);
        if (empty($list)) {
            //获取数据总数
            //返回结果
            $message = array(
                "msg" => '操作成功',
                "code" => 0,
                "data" => $list,
                "count" => $count,
            );
            unset($list, $count, $map, $param, $ids);
            return $message;
        } else {
            $exam_ids = array_column($list, 'exam_id');
            $user_ids = array_column($list, 'user_id');
            $examInfo = Db::name('exam')
                ->whereIn('id', $exam_ids)
                ->field('id,title')
                ->select()
                ->toArray();
            $userInfo = Db::name('member')
                ->whereIn('id', $user_ids)
                ->field('id,realname,examinee_number')
                ->select()
                ->toArray();
            foreach ($list as &$item) {
                $item['exam_title'] = '';
                $item['examinee_number'] = '';
                $item['realname'] = '';
                $item['usetime'] = floor($item['usetime'] / 60);
                foreach ($examInfo as $exam) {
                    if ($item['exam_id'] == $exam['id']) {
                        $item['exam_title'] = $exam['title'];
                    }
                }
                foreach ($userInfo as $user) {
                    if ($item['user_id'] == $user['id']) {
                        $item['realname'] = $user['realname'];
                        $item['examinee_number'] = $user['examinee_number'];
                    }
                }
            }
            $message = array(
                "msg" => '操作成功',
                "code" => 0,
                "data" => $list,
                "count" => $count,
            );
            unset($list, $count, $map, $param, $ids);
            return $message;
        }
        //获取数据总数
        //返回结果

    }

    /**
     * 导出数据
     */
    public function exportExamlog()
    {
        $sort = 'id desc';
        // 常规查询条件
        $param = request()->param();
        $map = [];
        if ($param) {
            // 筛选标题
            if (isset($param['userinfo']) && $param['userinfo']) {
                $userids = Db::name('member')
                    ->where('realname|examinee_number|idcard', 'like', "%{$param['userinfo']}%")
                    ->column('id');
                $map[] = ['user_id', 'in', $userids];
            }
            if (isset($param['exam_id']) && $param['exam_id']) {
                $map[] = ['exam_id', '=', $param['exam_id']];
            }
            // 筛选状态
            if (isset($param['status']) && $param['status']) {
                $map[] = ['status', '=', $param['status']];
            }
        }
        // 设置查询条件
        if (is_array($map)) {
            $map[] = ['mark', '=', 1];
        } elseif ($map) {
            $map .= " AND mark=1 ";
        } else {
            $map .= " mark=1 ";
        }
        $ids = $this->model
            ->where($map)
            ->order($sort)
            ->column("id");
        $map[] = ['id', 'in', $ids];
        $field = '';
        $list = $this->model->getAllInfo($map, $field);
        if (empty($list)) {
            //获取数据总数
            //返回结果
            $message = array(
                "msg" => '操作成功',
                "code" => 0,
                "data" => $list,
            );
            unset($list, $count, $map, $param, $ids);
            return $message;
        } else {
            $exam_ids = array_column($list, 'exam_id');
            $user_ids = array_column($list, 'user_id');
            $examInfo = Db::name('exam')
                ->whereIn('id', $exam_ids)
                ->field('id,title')
                ->select()
                ->toArray();
            $userInfo = Db::name('member')
                ->whereIn('id', $user_ids)
                ->field('id,realname,examinee_number')
                ->select()
                ->toArray();
            foreach ($list as &$item) {
                $item['exam_title'] = '';
                $item['examinee_number'] = '';
                $item['realname'] = '';
                $item['usetime'] = floor($item['usetime'] / 60);
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                foreach ($examInfo as $exam) {
                    if ($item['exam_id'] == $exam['id']) {
                        $item['exam_title'] = $exam['title'];
                    }
                }
                foreach ($userInfo as $user) {
                    if ($item['user_id'] == $user['id']) {
                        $item['realname'] = $user['realname'];
                        $item['examinee_number'] = $user['examinee_number'];
                    }
                }
                unset($item['exam_id'], $item['mark'], $item['user_id'], $item['problem_ids']);
            }
            $message = array(
                "msg" => '操作成功',
                "code" => 0,
                "data" => $list,
            );
            unset($list, $count, $map, $param, $ids);
            return $message;
        }


    }

    /**
     * 删除记录
     * @return array
     * @since 2020/11/12
     * @author 小码哥
     */
    public function delete()
    {
        // 参数
        $param = request()->param();
        // 记录ID
        $ids = getter($param, "id");
        if (empty($ids)) {
            return message("记录ID不能为空", false);
        }
        if (is_array($ids)) {
            // 批量删除
            $result = $this->model->deleteDAll($ids);
            if (!$result) {
                return message("删除失败", false);
            }
            return message("删除成功");
        } else {
            // 单个删除
            $info = $this->model->getInfo($ids);
            if ($info) {
                $result = $this->model->drop($ids);
                if ($result !== false) {
                    $this->deleteLog($ids);
                    return message();
                }
            }
            return message($this->model->getError(), false);
        }
    }

    /**
     * 删除答题记录
     */
    public function deleteLog($ids)
    {
        Db::name('exam_user_answer')
            ->where('exam_log_id', $ids)
            ->delete();
    }
}